<?php


namespace App\Logic\Order\Form;

use App\Core\BaseListForm;
use App\Core\Exception\DefaultException;
use App\Model\Member\MemberModel;
use App\Model\Member\MemberProfitScoreModel;
use App\Model\Order\OrderModel;
use App\Model\UserModel;
use App\Util\CommonHelper;
use App\Util\UserIdentityHelper;
use EasySwoole\Mysqli\QueryBuilder;

class OrderListForm extends BaseListForm
{
    public $id;
    public $user_id;
    public $username;
    public $group;
    public $order_state;
    public $date;
    public $order_date;
    public $duration;
    public $tracking_no;
    public $start_created_at;//订单创建时间 - 开始
    public $end_created_at;//订单创建时间 - 结束
    public $is_admin;//管理员

    /**
     * 订单列表
     * @return \App\Core\Output|array
     * @throws DefaultException
     * @throws \EasySwoole\Mysqli\Exception\Exception
     * @throws \EasySwoole\ORM\Exception\Exception
     * @throws \Throwable
     */
    public function lists()
    {
        $where = ['is_delete' => 0];
        if(UserIdentityHelper::getType() == UserModel::TYPE_INSIDE) {
            $this->is_admin = true;
            /**后台管理员*/
            if ($this->checkField($this->user_id)) {
                $where['user_id'] = $this->user_id;
            }
            if ($this->checkField($this->username)) {
                $subBuilder = QueryBuilder::subQuery();
                $subBuilder->where('username', $this->username);
                $subBuilder->get(MemberModel::create()->tableName(), null, "id");
                $where['user_id'] = [$subBuilder, 'in'];
            }
        }else{
            $this->user_id = UserIdentityHelper::getId();
            $where['user_id'] = $this->user_id;
            $where['order_time'] = [date('Y-m-d H:i:s'), '<'];
        }

        if ($this->checkField($this->id)) {
            $where['id'] = $this->id;
        }

        if ($this->checkField($this->order_date) && strtotime($this->order_date) > 0) {
            $where['order_date'] = $this->date;
        }
        if ($this->checkField($this->date) && strtotime($this->date) > 0) {
            $where['order_date'] = $this->date;
        }
        /**
        订单创建时间检索
         */
        if ($this->checkField($this->start_created_at) && $this->checkField($this->end_created_at)) {
            /**查询时间不能跨月*/
            $start_month = date('Y-m', strtotime($this->start_created_at));
            $end_month = date('Y-m', strtotime($this->end_created_at));
            if($start_month != $end_month) {
                throw new DefaultException('查询时间不能跨月');
            }
            $where['created_at'] = [[$this->start_created_at, $this->end_created_at], 'between'];
        }elseif ($this->checkField($this->start_created_at)) {
            $where['created_at'] = [$this->start_created_at, '>='];
        }elseif ($this->checkField($this->end_created_at)) {
            $where['created_at'] = [$this->end_created_at, '<='];
        }
        $model = OrderModel::makeQueryModel($where, [], $this->getPagination());

        /**@see OrderModel::member() */
        /**@see OrderModel::memberProfitScore() */
        $model->with(['member', 'memberProfitScore']);
        $model->order( 'order_time', 'DESC');

        $modelResult = $model->all();
        $list = [];
        foreach($modelResult as $v) {
            /** @var OrderModel $v*/
            $item = [
                'id'                => $v->id,
                'user_id'           => $v->user_id,
                'username'          => $v->member->username ?? '',
                'order_amount'      => $v->order_amount,
                'order_date'        => $v->order_date,
                'order_time'        => $v->order_time,
                'order_state'       => $v->order_state,
                'order_state_label' => OrderModel::getOrderStateDict($v->order_state),
                'user_profit'    => $v->user_profit,
//                'chain'    => $v->profit_chain,
                'group_profit'    => $v->memberProfitScore,
            ];

            if(!empty($v->memberProfitScore)) {
                $profitChain = [];
                $chain = json_decode($v->profit_chain, true);
                foreach($chain as $c){
                    $c['score'] = 0;
                    $c['type'] = '';
                    $c['remark'] = '';
                    $c['username'] = '';
                    $profitChain[$c['id']] = $c;
                }
                $item['group_profit'] = $profitChain;
                foreach ($v->memberProfitScore as $profit) {
                    /** @var MemberProfitScoreModel $profit*/
                    if ($profit->user_id == $v->user_id) {
                        $item['user_profit_score'] = $profit->score;
                    }

                    if (isset($profitChain[$profit->user_id])) {
                        $profitChain[$profit->user_id]['score'] = $profit->score;
                        $profitChain[$profit->user_id]['type'] = $profit->type;
                        $profitChain[$profit->user_id]['remark'] = $profit->remark;
                        $profitChain[$profit->user_id]['username'] = $profit->username;

                        $item['group_profit'] = $profitChain;
                    }
                }
            }
            $list[] = $item;
        }

        $userIds = [];
        foreach ($list as $item) {
            if (isset($item['group_profit']) && is_array($item['group_profit'])) {
                foreach (array_keys($item['group_profit']) as $id) {
                    $userIds[$id] = true;
                }
            }
        }
        $userIds = array_keys($userIds);
        if (!empty($userIds)) {
            $userIds = array_values($userIds);
            $userList = MemberModel::create()->where('id', $userIds, 'in')->field(['id', 'username'])->all();
            $userList = array_column($userList->toArray(), 'username', 'id');
            foreach ($list as &$item) {
                if (isset($item['group_profit']) && is_array($item['group_profit'])) {
                    foreach ($item['group_profit'] as &$profit) {
                        if (isset($userList[$profit['id']])) {
                            $profit['username'] = $userList[$profit['id']];
                        }
                    }
                    $item['group_profit'] = array_values($item['group_profit']);
                }
            }
        }

        $total = $model->lastQueryResult()->getTotalCount();
        $pagination = $this->getPagination();
        $pagination['total_count'] = $total;

        $result = [
            'list'       => $list,
            'pagination' => $pagination
        ];
        return $result;
    }

}
